package com.ruoyi.web.controller.system;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Counts;
import com.ruoyi.common.core.domain.Routers;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ExamPaperAnswerItemObject;
import com.ruoyi.system.domain.SysExamPaperAnswer;
import com.ruoyi.system.domain.wx.PaperTypeStatisticsVo;
import com.ruoyi.system.service.ISysExamPaperAnswerService;
import com.ruoyi.system.service.ISysExamPaperService;
import com.ruoyi.system.service.ISysSchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 首页
 *
 * @author ruoyi
 */
@RestController
public class SysIndexController {
    /**
     * 系统基础配置
     */
    @Autowired
    private RuoYiConfig ruoyiConfig;
    @Autowired
    private ISysSchoolService sysSchoolService;
    @Autowired
    private ISysExamPaperService sysExamPaperService;
    @Autowired
    private ISysExamPaperAnswerService sysExamPaperAnswerService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 访问首页，提示语
     */
    @RequestMapping("/")
    public String index() {
        return StringUtils.format("欢迎使用{}后台管理框架，当前版本：v{}，请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion());
    }


    /**
     * 首页统计方法接口  所有的xml 放在SysSchoolMapper.xml
     *
     * @return
     */
    @GetMapping("/home_statistics")
    public AjaxResult homeStatistics(SysExamPaperAnswer sysExamPaperAnswer) {
        if (redisCache.hasKey("homeStatistics")) {
            Object homeStatistics = redisCache.getCacheObject("homeStatistics");
            return AjaxResult.success(homeStatistics);
        }
        HomeStatistics homeStatistics = new HomeStatistics();
        // 路由接口  {type:"",router:""}
        List<Routers> routers = new ArrayList<>(6);
        routers.add(new Routers("答卷", "ANSWER", "/statistics/answer", "http://117.68.126.4:9000/public/lvluo/%E7%BC%96%E8%BE%91%E6%96%87%E4%BB%B6.png"));
        routers.add(new Routers("卷库", "PAPER", "/paper", "http://117.68.126.4:9000/public/lvluo/%E6%97%A5%E5%BF%97.png"));
        routers.add(new Routers("学校", "SCHOOL", "/school", "http://117.68.126.4:9000/public/lvluo/%E5%AD%A6%E6%A0%A1.png"));
        routers.add(new Routers("题目", "QUESTION", "/question/single", "http://117.68.126.4:9000/public/lvluo/%E5%8D%8F%E8%AE%AE.png"));
        homeStatistics.setRouters(routers);
        // 问卷数量 和 学校数量 {type:"", count:"",name :""}
        List<Counts> counts = new ArrayList<>(2);
        counts.add(new Counts("问卷数量", "PAPER", sysExamPaperService.count()));
        counts.add(new Counts("学校数量", "SCHOOL", sysSchoolService.count()));
        homeStatistics.setCounts(counts);
        // 学校答题情况
        List<SysExamPaperAnswer> sysExamPaperAnswerList = sysExamPaperAnswerService.selectSysExamPaperAnswerList(sysExamPaperAnswer);
        List<Counts> schoolCounts = sysExamPaperAnswerList.stream()
                .collect(Collectors.groupingBy(
                        SysExamPaperAnswer::getSchool, // 分组依据是年龄
                        Collectors.counting() // 计算每个组的数量
                )).entrySet()
                .stream()
                .map(entry -> new Counts(entry.getKey(), null, entry.getValue()))
                .collect(Collectors.toList());

        homeStatistics.setSchoolStatistics(schoolCounts);
        // 类型答卷数量
        List<SysDictData> questionClassification = DictUtils.getDictCache("question_classification");
        List<ExamPaperAnswerItemObject> examPaperAnswerItemObjectList = sysExamPaperAnswerList
                .stream()
                .map(SysExamPaperAnswer::getFrameTextContent)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        List<ExamPaperAnswerItemObject> list = getFrameTextContent(examPaperAnswerItemObjectList);
        // 根据 questionClassification 分组统计
        Map<String, List<ExamPaperAnswerItemObject>> classificationGroupMap = list
                .stream()
                .collect(Collectors.groupingBy(
                        item -> item.getQuestionClassification() != null ? item.getQuestionClassification() : "未分类"
                ));
        // 转换为 List<PaperTypeStatisticsVo> 格式
        List<PaperTypeStatisticsVo> classificationStatistics = classificationGroupMap.entrySet().stream()
                .map(entry -> {
                    String classification = entry.getKey();
                    List<ExamPaperAnswerItemObject> items = entry.getValue();
                    // 计算该分类的题目数量
                    long questionCount = items.size();
                    // 计算该分类的总分
                    long totalScore = items.stream()
                            .mapToLong(item -> {
                                if (item.getOptions() == null || item.getSelectedAnswer() == null) {
                                    return 0L;
                                }
                                // 将选中的答案转换为列表
                                List<String> selectedAnswers = Arrays.asList(item.getSelectedAnswer().split(","));

                                // 计算该答题项的总得分
                                return item.getOptions().stream()
                                        .filter(option -> selectedAnswers.contains(option.getPrefix()))
                                        .mapToLong(option -> option.getScore() != null ? option.getScore() : 0L)
                                        .sum();
                            }).sum();

                    // 根据字典数据获取分类名称
                    String classificationName = classification;
                    if (questionClassification != null) {
                        classificationName = questionClassification.stream()
                                .filter(dict -> classification.equals(dict.getDictValue()))
                                .map(dict -> dict.getDictLabel())
                                .findFirst()
                                .orElse(classification);
                    }
                    return PaperTypeStatisticsVo.builder()
                            .name(classificationName)        // name 分组名称
                            .count(questionCount)            // count 每组题目数量
                            .totalScore(totalScore)          // totalScore 每组总分
                            .build();
                }).sorted((a, b) -> a.getName().compareTo(b.getName()))  // 按名称排序
                .collect(Collectors.toList());
        // 输出题目分类统计
        System.out.println("=== 题目分类统计 ===");
        classificationStatistics.forEach(stat -> {
            System.out.println("分类: " + stat.getName() +
                    ", 题目数量: " + stat.getCount() +
                    ", 总分: " + stat.getTotalScore());
        });
        homeStatistics.setClassificationStatistics(classificationStatistics);
        redisCache.setCacheObject("homeStatistics", homeStatistics, 1800, TimeUnit.SECONDS);
        return AjaxResult.success(homeStatistics);
    }

    public List<ExamPaperAnswerItemObject> getFrameTextContent(List<ExamPaperAnswerItemObject> objects) {
        if (objects == null || objects.isEmpty()) {
            return new ArrayList<>();
        }
        Object first = objects.get(0);
        if (first instanceof ExamPaperAnswerItemObject) {
            // 已是强类型集合，直接返回（或浅拷贝）
            return objects;
        }
        // 处理 MyBatis/Jackson 映射为 LinkedHashMap 等非强类型的情况，避免 JSON 轮转
        java.util.List<ExamPaperAnswerItemObject> list = new java.util.ArrayList<>(objects.size());
        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
        for (Object obj : objects) {
            if (obj instanceof ExamPaperAnswerItemObject) {
                list.add((ExamPaperAnswerItemObject) obj);
            } else {
                ExamPaperAnswerItemObject examPaperAnswerItemObject = mapper.convertValue(obj, ExamPaperAnswerItemObject.class);
                list.add(examPaperAnswerItemObject);
            }
        }
        return list;
    }

    class HomeStatistics {
        private List<PaperTypeStatisticsVo> classificationStatistics;
        private List<Counts> schoolStatistics;
        private List<Counts> counts;
        private List<Routers> routers;

        public List<PaperTypeStatisticsVo> getClassificationStatistics() {
            return classificationStatistics;
        }

        public void setClassificationStatistics(List<PaperTypeStatisticsVo> classificationStatistics) {
            this.classificationStatistics = classificationStatistics;
        }

        public List<Counts> getCounts() {
            return counts;
        }

        public void setCounts(List<Counts> counts) {
            this.counts = counts;
        }

        public List<Routers> getRouters() {
            return routers;
        }

        public void setRouters(List<Routers> routers) {
            this.routers = routers;
        }

        public List<Counts> getSchoolStatistics() {
            return schoolStatistics;
        }

        public void setSchoolStatistics(List<Counts> schoolStatistics) {
            this.schoolStatistics = schoolStatistics;
        }
    }


}
